import eventlet
eventlet.monkey_patch()  

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO
import threading
from models import db

# 初始化 Flask 应用
app = Flask(__name__)

# 数据库配置
HOSTNAME = "127.0.0.1"
PORT = 3306
DATABASE = "iot_db"
USERNAME = "root"
PASSWORD = "789852"
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化数据库
db.init_app(app)
migrate = Migrate(app, db)

# 初始化 SocketIO
socketio = SocketIO(app)

# 注册路由
from routes import register_routes

register_routes(app, socketio)

# 启动mqtt订阅环境数据线程
from data_subscriber import start_mqtt_client
mqtt_thread = threading.Thread(target=start_mqtt_client, args=(app,), daemon=True)
mqtt_thread.start()

# 启动webSocket
if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=False)